#include "Mutex.hpp"
using namespace std;

#define NUM 5

int tickets=100;

pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;

class threadData
{
public:
    threadData(int i)
    {
        threadname="thread-"+to_string(i)+"号";
    }
string threadname;
};

// __thread threadData d;

void* getickets(void *args)
{
    threadData* t=static_cast<threadData*>(args);
    const char*name =t->threadname.c_str();

    while(1)
    {
        
            if(tickets>0)
            {
                LockMutex _mutex(&lock);
                tickets--;
                printf("%s 抢到一张票，还剩下 %d张票\n",name,tickets);
            }
            else{
                break;
            }
        
        usleep(1000);
    }
    printf("quit,%s\n",name);
    pthread_exit(nullptr);
}

int main()
{
    vector<pthread_t> v;
    vector<threadData*> data;
    for(int i=1;i<=NUM;i++)
    {
        pthread_t tid;
        threadData* tmp=new threadData(i);
        pthread_create(&tid,nullptr,getickets,tmp);
        v.push_back(tid);
        data.push_back(tmp);
    }

    for(auto i:v)
    {
        pthread_join(i,nullptr);
    }

    for(auto i:data)
    {
        delete i;
    }

    pthread_exit(nullptr);
}
